package JavaEE.ManyThread9;
import java.util.*;
import java.util.concurrent.Semaphore;

// 信号量.
public class Demo1 {
    public static int sum = 0;
    public static void main(String[] args) throws InterruptedException{
        // 信号量,这个代表初始化信号量为1.
        Semaphore semaphore = new Semaphore(1);
        semaphore.acquire(); // 信号量 -1
        semaphore.release(); // 信号量 +1
        // 类似于"停车站门口的车辆计数器",有车进入则+1,有车出去则-1

        // "信号量":类似于"锁"概念的进一步延申
        Thread t1 = new Thread(() -> {
            for(int i = 0;i < 50000;i++){
                try{
                    // 相当于加锁 -> "信号量-1"
                    semaphore.acquire();
                    sum++;
                    // 相当于解锁 -> "信号量+1"
                    semaphore.release();
                }catch(InterruptedException e) {
                    e.printStackTrace();
                };
            }
        });
        Thread t2 = new Thread(() -> {
            for(int i = 0;i < 50000;i++){
                try{
                    semaphore.acquire();
                    sum++;
                    semaphore.release();
                }catch(InterruptedException e) {
                    e.printStackTrace();
                };
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        // 100000
        System.out.println(sum);
    }
}
